package com.echo.echovividlive.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWT;
import com.echo.echovividlive.common.UserThread;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;


@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (request.getMethod().equals("OPTIONS")){
            return true;
        }
        String header = request.getHeader("Authorization");
        if (StrUtil.isBlank(header)){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        // 获取用户id并保存
        try {
            Object userId = JWT.of(header).getPayload("userId");
            log.info("当前用户id userId:{}",userId);
            UserThread.setUserId(Integer.parseInt(userId.toString()));
        }catch (Exception e){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThread.removeUserId();
    }
}
